import time

from flask_restful import Api,Resource,marshal,reqparse
from flask import Blueprint,jsonify,g
from models import db
from common.uitils.login_utils import login_required
from models.user import *
from common.model_fields.user import *
comments_bp = Blueprint('comments', __name__, url_prefix='/comments')

api = Api(comments_bp)


class AllComments(Resource):
    def get(self, nid):
        comments = Comment.query.filter_by(article_id=nid).all()
        comments_ = []
        for i in comments:
            user = UserModel.query.get(i.user_id)
            comments_data = {
                'nick_name': user.uname,
                'create_data': i.ctime,
                'content': i.content,
                'parent_id': i.cmid,
                'profile_photo': user.profile_photo
            }
            comments_.append(comments_data)
        return jsonify(data=comments_, message='ok')

    @login_required
    def post(self, nid):
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument('content')
        parser.add_argument('parent_id')
        args = parser.parse_args()
        content = args.get('content')
        parent_id = args.get('parent_id')
        comment = Comment(user_id=uid, article_id=nid, content=content)
        db.session.add(comment)
        db.session.commit()
        return jsonify(message='ok')


api.add_resource(AllComments, '/post_comment/<int:nid>')

